import axios from "axios";
import store from "@/store"


const instance = axios.create({
    baseURL: "/api",
    timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(config => {

    let token = localStorage.getItem("x-auth-token")
    if (token) {
        config.headers["x-auth-token"] = token;
    }

    return config
}, err => {
    return Promise.reject(err)
})

// 响应拦截器
instance.interceptors.response.use(res => {    //200

    let ret = res.data;

    if (ret.errCode !== 0) {
        // 提示
        // let action = {
        //     type: "showAlert",
        //     value: {
        //         showAlert: true,
        //         alertType: "warning",
        //         alertContent: ret.message
        //     }
        // }
        // store.dispatch(action);
        // setTimeout(() => {
        //     store.dispatch({
        //         type: "hideAlert"
        //     })
        // }, 1500)
        alert(ret.message);
    }
    return ret
}, err => {     //500
    // console.log("11111");
    // console.log(typeof err);      //object
    // for (var key in err) {
    //     console.log(key, err[key]);
    // }
    let action = {
        type: "showAlert",
        value: {
            showAlert: true,
            alertType: "warning",
            alertContent: err.response.data.message
        }
    }
    store.dispatch(action);
    setTimeout(() => {
        store.dispatch({
            type: "hideAlert"
        })
    }, 1500)
    // alert(err.response.data.message);

    // 错误码
    if (err.response.data.errCode === 1002) {
        return err
        // 直接回到组件中的await继续执行,而组件中的res 接收这个er对象
    }

    return Promise.reject(err)    // 直接抛出错误,在浏览器控制面板上报红
})

export default instance